﻿using System;
using System.Net;
using System.Threading;
using System.IO;
using System.Collections.Specialized;

namespace WebLearningFS
{
	public class CookieAwareWebClient : WebClient
	{
		public CookieContainer m_container = new CookieContainer();

		protected override WebRequest GetWebRequest(Uri address)
		{
			WebRequest request = base.GetWebRequest(address);
			if (request is HttpWebRequest)
			{
				var httpRequest = request as HttpWebRequest;
				httpRequest.CookieContainer = m_container;
			}
			return request;
		}

		protected override WebResponse GetWebResponse(WebRequest request)
		{
			WebResponse response = base.GetWebResponse(request);
			if (response is HttpWebResponse)
			{
				var tmp = response as HttpWebResponse;
				m_container.Add(tmp.ResponseUri, tmp.Cookies);
			}
			return response;
		}

		public int GetFileSize(string URL)
		{
			HttpWebRequest req = HttpWebRequest.Create(URL) as HttpWebRequest;
			req.Method = "HEAD";
			req.Proxy = null;
			req.CookieContainer = m_container;
			HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
			m_container.Add(resp.ResponseUri, resp.Cookies);
			resp.Close();
			int contentLength;
			if (int.TryParse(resp.Headers.Get("Content-Length"), out contentLength))
			{
				return contentLength;
			}
			return 0;
		}

		public void PostFile(byte[] buffer, string filename, string URL, NameValueCollection nvc)
		{
			string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
			byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

			HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(URL);
			wr.ContentType = "multipart/form-data; boundary=" + boundary;
			wr.Method = "POST";
			wr.KeepAlive = true;
			//wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
			
			wr.Proxy = null;
			wr.CookieContainer = m_container;

			Stream rs = wr.GetRequestStream();
			string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
			foreach (string key in nvc.Keys)
			{
				rs.Write(boundarybytes, 0, boundarybytes.Length);
				string formitem = string.Format(formdataTemplate, key, nvc[key]);
				byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
				rs.Write(formitembytes, 0, formitembytes.Length);
			}
			rs.Write(boundarybytes, 0, boundarybytes.Length);
			//string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
			string headerTemplate = "Content-Disposition: form-data; name=\"upfile\"; filename=\"{0}\"\r\n\r\n";

			//string header = string.Format(headerTemplate, paramName, filename, contentType);
			string header = string.Format(headerTemplate, filename);

			byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
			rs.Write(headerbytes, 0, headerbytes.Length);
            rs.Write(buffer, 0, buffer.Length);

			byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
			rs.Write(trailer, 0, trailer.Length);
			rs.Close();

			WebResponse wresp = null;
			try
			{
				wresp = wr.GetResponse();
				Stream stream2 = wresp.GetResponseStream();
				StreamReader reader2 = new StreamReader(stream2, System.Text.Encoding.GetEncoding("GB18030"));
				string fullResponse = reader2.ReadToEnd();
				wresp.Close();
				Console.WriteLine("Post response: " + fullResponse);
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.ToString());
				if(wresp != null) 
				{
					wresp.Close();
					wresp = null;
				}
			}
			finally
			{
				wr = null;
			}			
		}
	}
}
